package com.example.forum.common;

import com.example.forum.exception.ApplicationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常处理
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public AppResult applicationException(ApplicationException e) {
        e.printStackTrace();
        log.error(e.getMessage());

        if(e.getMessage() == null || e.getMessage().equals("")) {
            return AppResult.fail(ResultCode.ERROR_SERVICES);
        }
        return AppResult.fail(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult exception(Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());

        if(e.getMessage() == null || e.getMessage().equals("")) {
            return AppResult.fail(ResultCode.ERROR_SERVICES);
        }
        return AppResult.fail(e.getMessage());
    }


}
